// pages/submitorder/submitorder.js
const app = getApp();
Page({
    /**
     * 页面的初始数据
     */
    data: {
        network:false,
        coupon:null,
        index:0,
        coupon_money:0,
        loadCoupon:false,
        range:[] ,
        order_num:null
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        var that = this;
        var param = JSON.parse(options.param);
        this.setData({
            param:param,
            userInfo:app.globalData.userInfo
        });
        //判断是参团者还是开团者
        var leader = param.group_id == undefined ? true : false;
        this.setData({
            leader:leader
        });
        this.getAddress();
        //计算金额
        this.statistics();
        //加载优惠券数据
        if(!leader){
            if ( param.is_support_coupon){
                this.getCouponList();
            }
        }else{
            if (param.type == 1 && param.is_support_coupon){
                this.getCouponList();
            }
        }
        app.event.on('addressChange', that, function (data) {
            that.setData({
                address: data
            })
        });
    },

    //获取优惠券
    getCouponList:function(){
        var that = this;
        var data = {
            user_id: app.globalData.userInfo.id,
            goods_id: that.data.param.goods_id,
            money:that.data.pay_money
        }
        app.common.apiRequest('api/coupon/usableCoupon',data,function(res){
            var coupon = res.data;
            var range = ['不使用优惠券'];
            for(var i in coupon){
                range.push(coupon[i].money);
            }
            that.setData({
                coupon: coupon,
                range: range,
                loadCoupon:true
            });
        })
    },

    //选择优惠券
    bindCouponChange:function(e){
        var index = e.detail.value;
        var coupon_money = 0;
        var range = this.data.range;
        if(index != 0){
            coupon_money = range[index];
        }
        this.setData({
            coupon_money:coupon_money,
            index:index
        });
        //计算金额
        this.statistics();
    },

    //统计金额
    statistics:function(){
        var that = this;
        //团类型
        var type = that.data.param.type
        //参团者还是开团者
        var leader = that.data.leader;
        //支付金额 1.团长 1)神秘团(团长不可使用优惠券) 团长价 * 购买数量 + 运费 2)普通团 团购价*购买数量 - 立减金 + 运费 - 优惠券 2.参团者  团购价*购买数量 + 运费 - 优惠券
        //type 1为普通团 2为神秘团 3为超级团长团
        var pay_money = 0.00;
        var param = that.data.param;
        if(type == 1){
            if(leader){
                pay_money = param.group_price * param.num - param.cut_money - that.data.coupon_money;
            }else{
                pay_money = param.group_price * param.num - that.data.coupon_money;
            }
        }else{
            if (leader) {
                pay_money = param.leader_price * param.num;
            } else {
                pay_money = param.group_price * param.num - this.data.coupon_money;
            }
        }
        pay_money = pay_money.toFixed(2);
        if(pay_money < 0){
            pay_money = 0.01;
        }
        that.setData({
            pay_money: pay_money
        });
    },

    onUnload:function(){
        var that = this;
        app.event.remove('addressChange',that);
    },

    //获取用户地址
    getAddress:function(){
        var that = this;
        var data = {
            user_id:app.globalData.userInfo.id
        };
        app.common.apiRequest('api/address/index',data,function(res){
            var address = null;
            if(res.data.length >= 1){
                address = res.data[0];
            }
            that.setData({
                address: address,
                network:true
            });
        })
    },

    /**
     * 表单提交
     */
    formSubmit: function (e) {
        var that = this;
        /*表单数据验证 */
        var result = that.validate(e);
        if (!result.status) {
            wx.showToast({
                title: result.msg,
                icon: 'none'
            });
            return;
        }
        that.setData({
            loading: true
        });
        var data = e.detail.value;
        data.formId = e.detail.formId;
        /*创建订单 */
        app.common.apiRequest('api/order/createOrder', data, function (res) {
            if (res.code != '1') {
                wx.showToast({
                    title: res.msg,
                    icon: 'none',
                    duration: 2500
                })
                that.setData({
                    loading: false,
                });
            } else {
                that.setData({
                    order_num: res.data.order_num,
                    group_id: res.data.group_id
                });
                //支付
                that.pay();
            }
        });
    },

    //继续支付
    pay:function(){
        var that = this;
        var data = {
            order_num: that.data.order_num
        };
        that.setData({
            loading:true
        });
        app.common.apiRequest('api/WX/prePay', data, function (result) {
            if (result.code != '1') {
                wx.showToast({
                    title: result.msg,
                    icon:'none',
                    duration:2500,
                    complete:function(){
                        that.setData({
                            loading: false,
                        });
                    }
                })
                return;
            }
            /*唤起微信支付 */
            wx.requestPayment({
                timeStamp: result.data.timeStamp,
                nonceStr: result.data.nonceStr,
                package: result.data.package,
                signType: result.data.signType,
                paySign: result.data.paySign,
                complete: function (rs) {
                    that.setData({
                        loading: false
                    });
                    if (rs.errMsg == "requestPayment:fail") {
                        wx.showToast({
                            title: rs.err_desc,
                            icon:'none'
                        });
                    } else if (rs.errMsg == "requestPayment:fail cancel") {

                    } else {
                        //支付成功跳转拼团详情页
                        if(that.data.param.group_id == undefined){
                            wx.redirectTo({
                                url: '../mygroupdetail/mygroupdetail?group_id=' + that.data.group_id,
                            })
                        }else{
                            wx.navigateBack({});
                        }
                    }
                }
            })
        })
    },

    /**
     * 验证数据
     */
    validate: function (e) {
        var that = this;
        var data = e.detail.value;
        var result = {
            status: true,
            msg: ''
        };
        var param = {};
        //数据验证
        var temp = {
            name: {
                key: data.name,
                reg: [/\S/],
                msg: ['请选择地址'],
            }
        }
        param = Object.assign(param, temp);
        for (var i in param) {
            for (var j in param[i].reg) {
                if (!param[i].reg[j].test(param[i].key)) {
                    result.status = false;
                    result.msg = param[i].msg[j];
                    return result;
                }
            }
        }
        return result;
    },
})